﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using WebHttpApi.WebHttpApi.Core;

namespace WebHttpApi.WebHttpApi.HttpApi
{
    /// <summary>
    /// TyGPRS 的摘要说明：GPRS水表指令类
    /// </summary>
    public class TyGPRS
    {
        public static string str_MeterId = "";                 //表地址逆序排列（8位表号GPRS）
        public static string str_Comm = "";                    //命令串
        public static string str_CommPam = "";                 //参数串

        public static string str_zxjg = "0";                   //执行结果  -  0：未执行 | 1：已执行
        public static string str_xyjx = "";                    //协议解析  -  什么命令（日志）
        public static string str_rzlx = "存储";                //日志类型  -  存储：命令写数据库（日志）
        public static string str_xymc = "";                    //协议名称  -  命令类型名称： 控阀、休眠等（日志）
        public static string str_oper = "WebHttpApi";          //操作员    -  指令、日志

        public static string str_Result = "";

        public static string GPRS_Comm(string MeterType, string MeterId, string Type, string CommPam)
        {
            str_xyjx = "";
            str_xymc = "";

            if (MeterId != "" && Type != "")
            {
                try
                {
                    str_MeterId = "";
                    for (int i = 0; i < MeterId.Length / 2; i++)
                    {
                        string str_meterid = MeterId.Substring(2 * i, 2);
                        str_meterid = Convert.ToString(Convert.ToInt64(str_meterid), 16);
                        str_meterid = "00" + str_meterid;
                        str_meterid = str_meterid.Substring(str_meterid.Length - 2);

                        str_MeterId = str_meterid + str_MeterId;
                    }

                    switch (Type)
                    {
                        //控阀指令
                        //Type：07 | 7
                        case "67":
                        case "7":
                            {
                                if (Type == "67")
                                {
                                    Type = "7";
                                }

                                if (CommPam == "85")
                                {
                                    str_CommPam = "55";
                                    str_xyjx = "开阀";
                                }
                                else if (CommPam == "153")
                                {
                                    str_CommPam = "99";
                                    str_xyjx = "关阀";
                                }
                                else
                                {
                                    str_Result = "参数错误";
                                    break;
                                }
                                str_xymc = "控阀";
                            
                                if (MeterType == "11")
                                {
                                    str_Comm = str_MeterId + "0710000001" + str_CommPam;
                                    str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                    str_Comm = "1B06" + str_Comm;
                                    str_Comm = str_Comm.ToUpper();

                                    str_Result = GPRS_sql(MeterId, Type);
                                }
                                else
                                {
                                    str_Result = "不支持";
                                }

                                break;
                            }

                        //参数设置
                        //Type：16 | 22
                        //CommPam：00 00  (1、用户状态；2、脉冲当量；)
                        case "22":
                            {
                                str_xyjx = "参数设置[" + CommPam + "]";
                                str_xymc = "参数设置";

                                try
                                {
                                    string[] str = CommPam.Split(':');

                                    string str_yhzt = str[0];
                                    str_yhzt = "00" + str_yhzt;
                                    str_yhzt = str_yhzt.Substring(str_yhzt.Length - 2);

                                    string str_mcdl = str[1];
                                    str_mcdl = "00" + str_mcdl;
                                    str_mcdl = str_mcdl.Substring(str_mcdl.Length - 2);

                                    str_CommPam = str_yhzt + str_mcdl;
                                }
                                catch
                                {
                                    str_Result = "参数错误";
                                    break;
                                }

                                str_Comm = str_MeterId + "1610000002" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //底数设置
                        //Type：08 | 8
                        //CommPam：000000 （3字节HEX：低在前，脉冲数,根据脉冲当量计算）
                        case "8":
                            {
                                str_xyjx = "底数设置[" + CommPam + "]";
                                str_xymc = "底数设置";

                                string Meter_mcdl;
                                int str_mcdl;

                                try
                                {
                                    string sql = "select ybdz,mcdl from rp_meter_jk where ybdz='" +
                                                    MeterId + "'";

                                    System.Data.DataTable Meter_Data = WebSdkCore.select(sql);

                                    if (Meter_Data.Rows.Count > 0)
                                    {
                                        Meter_mcdl = Meter_Data.Rows[0]["mcdl"].ToString();
                                        Meter_mcdl = Regex.Replace(Meter_mcdl, @"[^0-9,.]+", "");

                                        if (Meter_mcdl == "0.1")
                                        {
                                            str_mcdl = 1;
                                        }
                                        else if (Meter_mcdl == "0.01")
                                        {
                                            str_mcdl = 10;
                                        }
                                        else if (Meter_mcdl == "0.001")
                                        {
                                            str_mcdl = 100;
                                        }
                                        else
                                        {
                                            str_Result = "参数错误";
                                            break;
                                        }

                                        str_CommPam = Convert.ToInt64(Convert.ToDouble(CommPam) * str_mcdl).ToString("x");
                                        str_CommPam = "000000" + str_CommPam;
                                        str_CommPam = str_CommPam.Substring(str_CommPam.Length - 6);

                                        str_CommPam = str_CommPam.Substring(4, 2) +
                                                      str_CommPam.Substring(2, 2) +
                                                      str_CommPam.Substring(0, 2);
                                    }
                                    else
                                    {
                                        str_Result = "仪表不存在";
                                        break;
                                    }
                                }
                                catch
                                {
                                    str_Result = "参数错误";
                                    break;
                                }

                                str_Comm = str_MeterId + "0810000003" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //设表地址
                        //Type：0E | 14
                        //CommPam：8位新仪表地址号
                        case "14":
                            {
                                str_xyjx = "设表地址[" + CommPam + "]";
                                str_xymc = "设表地址";

                                if (CommPam.Length == 8)
                                {
                                    try
                                    {
                                        str_MeterId = "";
                                        for (int i = 0; i < CommPam.Length / 2; i++)
                                        {
                                            string str_meterid = CommPam.Substring(2 * i, 2);
                                            str_meterid = Convert.ToString(Convert.ToInt64(str_meterid), 16);
                                            str_meterid = "00" + str_meterid;
                                            str_meterid = str_meterid.Substring(str_meterid.Length - 2);

                                            str_MeterId = str_meterid + str_MeterId;
                                        }

                                        str_CommPam = str_MeterId;
                                    }
                                    catch
                                    {
                                        str_Result = "参数错误";
                                        break;
                                    }

                                    str_Comm = str_MeterId + "0E10000004" + str_CommPam;
                                    str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                    str_Comm = "1B06" + str_Comm;
                                    str_Comm = str_Comm.ToUpper();

                                    str_Result = GPRS_sql(MeterId, Type);
                                }
                                else
                                {
                                    str_Result = "参数错误";
                                }
                                break;
                            }

                        //设置IP端口
                        //Type：0F | 15
                        //CommPam：IP:端口
                        case "15":
                            {
                                str_xyjx = "设置IP端口[" + CommPam + "]";
                                str_xymc = "设置IP端口";

                                try
                                {
                                    string[] str = CommPam.Split(':');

                                    string str_ip = str[0];
                                    string[] ip = str_ip.Split('.');

                                    string str_ip01 = "00" + Convert.ToInt64(ip[0]).ToString("x");
                                    str_ip01 = str_ip01.Substring(str_ip01.Length - 2);
                                    string str_ip02 = "00" + Convert.ToInt64(ip[1]).ToString("x");
                                    str_ip02 = str_ip02.Substring(str_ip02.Length - 2);
                                    string str_ip03 = "00" + Convert.ToInt64(ip[2]).ToString("x");
                                    str_ip03 = str_ip03.Substring(str_ip03.Length - 2);
                                    string str_ip04 = "00" + Convert.ToInt64(ip[3]).ToString("x");
                                    str_ip04 = str_ip04.Substring(str_ip04.Length - 2);

                                    str_ip = str_ip01 + str_ip02 + str_ip03 + str_ip04;

                                    string str_dk = str[1];
                                    str_dk = Convert.ToInt64(str_dk).ToString("x");
                                    str_dk = "0000" + str_dk;
                                    str_dk = str_dk.Substring(str_dk.Length - 4);

                                    str_CommPam = str_ip + str_dk;
                                }
                                catch
                                {
                                    str_Result = "参数错误";
                                    break;
                                }

                                str_Comm = str_MeterId + "0F10000006" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //读取IP端口
                        //Type：12 | 18
                        case "18":
                            {
                                str_xyjx = "读取IP端口";
                                str_xymc = "读取IP端口";

                                str_Comm = str_MeterId + "1210000000";
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //设表时间:指令下发写当前时间
                        //Type：06 | 6
                        case "6":
                            {
                                str_xyjx = "设表时间";
                                str_xymc = "设表时间";

                                try
                                {
                                    string str_year = DateTime.Now.ToString("yyyy");
                                    str_year = "0000" + str_year;
                                    str_year = str_year.Substring(str_year.Length - 4);

                                    string str_month = DateTime.Now.ToString("MM");
                                    str_month = "00" + str_month;
                                    str_month = str_month.Substring(str_month.Length - 2);

                                    string str_day = DateTime.Now.ToString("dd");
                                    str_day = "00" + str_day;
                                    str_day = str_day.Substring(str_day.Length - 2);

                                    string str_hour = DateTime.Now.ToString("HH");
                                    str_hour = "00" + str_hour;
                                    str_hour = str_hour.Substring(str_hour.Length - 2);

                                    string str_minute = DateTime.Now.ToString("mm");
                                    str_minute = "00" + str_minute;
                                    str_minute = str_minute.Substring(str_minute.Length - 2);

                                    string str_second = DateTime.Now.ToString("ss");
                                    str_second = "00" + str_second;
                                    str_second = str_second.Substring(str_second.Length - 2);

                                    str_CommPam = str_year + str_month + str_day + str_hour + str_minute + str_second;
                                }
                                catch
                                {
                                    str_Result = "写指令失败";
                                    break;
                                }

                                str_Comm = str_MeterId + "0610000007" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);
                                break;
                            }
                            
                        //设上报周期
                        //Type：18 | 24
                        //CommPam：上线间隔（小时）:时（0-23）:分（0-59）
                        case "24":
                            {
                                str_xyjx = "设上报周期[" + CommPam + "]";
                                str_xymc = "设上报周期";

                                try
                                {
                                    string[] str = CommPam.Split(':');

                                    string str_sbjg = str[0];
                                    if (0 <= Convert.ToInt64(str_sbjg) && Convert.ToInt64(str_sbjg) <= 144)
                                    {
                                        str_sbjg = "00" + Convert.ToInt64(str_sbjg).ToString("x");
                                        str_sbjg = str_sbjg.Substring(str_sbjg.Length - 2);
                                    }
                                    else
                                    {
                                        str_Result = "参数错误";
                                        break;
                                    }

                                    string str_hour = "00";
                                    string str_minute = "00";

                                    if (str_sbjg == "00")
                                    {
                                        str_hour = str[1];
                                        if (0 <= Convert.ToInt64(str_hour) && Convert.ToInt64(str_hour) <= 23)
                                        {
                                            str_hour = "00" + str_hour;
                                            str_hour = str_hour.Substring(str_hour.Length - 2);
                                        }
                                        else
                                        {
                                            str_Result = "参数错误";
                                            break;
                                        }

                                        str_minute = str[2];
                                        if (0 <= Convert.ToInt64(str_minute) && Convert.ToInt64(str_minute) <= 59)
                                        {
                                            str_minute = "00" + str_minute;
                                            str_minute = str_minute.Substring(str_minute.Length - 2);
                                        }
                                        else
                                        {
                                            str_Result = "参数错误:上线间隔:0-144(小时),上限时:0-23(时),上线分:0-59(分)";
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        str_hour = "00";
                                        str_minute = "00";
                                    }

                                    str_CommPam = str_sbjg + str_hour + str_minute;
                                }
                                catch
                                {
                                    str_Result = "参数错误";
                                    break;
                                }

                                str_Comm = str_MeterId + "1810000003" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //设置APN
                        //Type：37 | 55
                        //CommPam：APN
                        case "55":
                            {
                                str_xyjx = "设置APN";
                                str_xymc = "设置APN";

                                string str_len = CommPam.Length.ToString("x");
                                string str_apn = "";

                                byte[] array_apn = System.Text.Encoding.ASCII.GetBytes(CommPam);

                                string asc_apn = null;
                                for (int i = 0; i < array_apn.Length; i++)
                                {
                                    int asc_code = (int)(array_apn[i]);
                                    asc_apn += Convert.ToString(asc_code, 16);
                                }

                                str_CommPam = str_len + str_apn;

                                str_Comm = str_MeterId + "3710000001" + str_CommPam;
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }

                        //读取APN
                        //Type：38 | 56
                        case "56":
                            {
                                str_xyjx = "读取APN";
                                str_xymc = "读取APN";

                                str_Comm = str_MeterId + "381000000100";
                                str_Comm = str_Comm + WebSdkCore.ToModbusCRC16(str_Comm, true);
                                str_Comm = "1B06" + str_Comm;
                                str_Comm = str_Comm.ToUpper();

                                str_Result = GPRS_sql(MeterId, Type);

                                break;
                            }
                    }
                }
                catch
                {
                    str_Result = "参数错误";
                }
            }
            return str_Result;
        }

        public static string GPRS_sql(string MeterId, string Type)
        {
            DateTime str_dt = DateTime.Now;

            bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_cx(ybdz,mllx,mlnr,bcsj,zxjg) values ('" +
                                                                MeterId + "','" +
                                                                Type + "','" +
                                                                str_Comm + "','" +
                                                                str_dt + "','" +
                                                                str_zxjg + "')");

            if (operatorlog == true)
            {
                operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                    MeterId + "','" +
                                                                    str_Comm + "','" +
                                                                    str_xyjx + "','" +
                                                                    str_dt + "','" +
                                                                    str_rzlx + "','" +
                                                                    str_xymc + "','" +
                                                                    str_oper + "')");
                if (operatorlog == true)
                {
                    str_Result = "成功";
                }
                else
                {
                    str_Result = "写日志失败";
                }
            }
            else
            {
                str_Result = "写指令失败";
            }

            return str_Result;
        }
    }
}